<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Loan;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Models\{Book, User};


class LoanController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Loan(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('book_id','书籍名称')->display(function($item) {
                return Book::find($item)->title;
            });
            $grid->column('user_id','借书人')->display(function($item) {
                return User::find($item)->name;
            });
            $grid->column('loan_date');
            $grid->column('return_date');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
        
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
        
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Loan(), function (Show $show) {
            $show->field('id');
            $show->field('book_id');
            $show->field('user_id');
            $show->field('loan_date');
            $show->field('return_date');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Loan(), function (Form $form) {
            $form->display('id');
            $form->select('book_id')->options($this->books());
            $form->select('user_id')->options($this->users());
            $form->datetime('loan_date');
            $form->datetime('return_date');
            $form->display('created_at');
            $form->display('updated_at');
        });
    }

    public function books() {
        return Book::all()->pluck('title', 'id')->toArray();
    }

    public function users() {
        return User::all()->pluck('name', 'id')->toArray();
    }
}
